<script setup>
import { useRoute } from "vue-router";
import { onMounted, ref, watch } from "vue";
import { areaList } from "@vant/area-data";
import api from "@/api/api.js";
import Steps from "@/components/enroll/steps.vue";
import { showDialog } from "vant";
import { useUserStore } from "@/stores/user.store";
import { storeToRefs } from "pinia";
import { useNationStore } from "@/stores/index.js";

const { userData } = storeToRefs(useUserStore());
const { nation_list } = storeToRefs(useNationStore());

const route = useRoute();
const enrollId = ref(route.query.id); //每项活动的id
const enrollPrice = ref(route.query.price); //每项活动报名费
const stepActive = ref(1); //步骤，1填写资料，2报名缴费，3线下复核，4完成报名
const isReg = ref(0); //是否填写资料，0未填写，1已填写
const payStatus = ref(0); //是否缴费，0未缴费，1已缴费，2退款，3无需退款
const status = ref(0); //是否复核，0未复核，1已复核

const get_EnrollInfo = async () => {
  await api.getEnrollInfo({ id: enrollId.value }).then(async (res) => {
    isReg.value = res.isReg;
    if (isReg.value === 1) {
      //将填写过的数据渲染到页面中
      name.value = res.name;
      sex.value = res.sex;
      phone.value = res.phone;
      nation.value = res.nation;
      place.value = res.place;
      cardno.value = res.cardno;
      option1.value = res.option1;
      option2.value = res.option2;
      option3.value = res.option3;
      option4.value = res.option4;
      stepActive.value = res.step;
      payStatus.value = res.payStatus;
      status.value = res.status;

      //三个option下拉框获取数据
      await api.getSchool({ option: option1.value }).then((res) => {
        option2_list.value = [
          ...res.map((item, index) => ({
            text: item,
            value: index + 1,
          })),
        ];
      });

      await api.getSubject({ school: option2.value }).then((res) => {
        option3_list.value = [
          ...res.map((item, index) => ({
            text: item,
            value: index + 1,
          })),
        ];
      });

      await api
        .getMajor({ school: option2.value, subject: option3.value })
        .then((res) => {
          option4_list.value = [
            ...res.map((item, index) => ({
              text: item,
              value: index + 1,
            })),
          ];
        });
    }
  });
};

//报名信息表单
const name = ref(""); //姓名
const sex = ref(""); //性别
const setSex = (value) => {
  //复核状态前皆可修改
  if (status.value === 0) {
    sex.value = value;
  }
};
const phone = ref(""); //手机号
const nation = ref(""); //民族
const showNation = ref(false);
const nationList = ref(nation_list); //民族列表
const place = ref(""); //籍贯
const showArea = ref(false);

const onNationConfirm = ({ selectedOptions }) => {
  if (status.value === 0) {
    nation.value = selectedOptions[0]?.text;
    showNation.value = false;
  }
};

const onPlaceConfirm = ({ selectedOptions }) => {
  //复核状态前皆可修改
  if (status.value === 0) {
    showArea.value = false;
    place.value = selectedOptions.map((item) => item.text).join("/");
  }
};

const cardno = ref(""); //身份证

// 选项 1
const option1 = ref("");
//选择后立即发送请求，并将数据渲染到option2_list中
const setOption1 = async (value) => {
  if (status.value === 0) {
    option1.value = value;
    //重置
    option2.value = "";
    option2_list.value = [];
    option3.value = "";
    option3_list.value = [];
    option4.value = "";
    option4_list.value = [];

    let params = {
      option: option1.value,
    };
    const res = await api.getSchool(params);
    option2_list.value = [
      ...res.map((item, index) => ({
        text: item,
        value: index + 1,
      })),
    ];
  }
};

// 请选择报名院校
const option2 = ref("");
const show_option2 = ref(false);
const option2_list = ref([]);
//选择后发送请求，并将数据渲染到option3_list中
const onOptionConfirm2 = async ({ selectedOptions }) => {
  if (status.value === 0) {
    option2.value = selectedOptions[0]?.text;
    show_option2.value = false;
    //重置
    option3.value = "";
    option3_list.value = [];
    option4.value = "";
    option4_list.value = [];

    let params = {
      school: option2.value,
    };
    const res = await api.getSubject(params);
    option3_list.value = [
      ...res.map((item, index) => ({
        text: item,
        value: index + 1,
      })),
    ];
  }
};

// 选项 3
const option3 = ref("");
const show_option3 = ref(false);
const option3_list = ref([]);
//同理，渲染选项4_list
const onOptionConfirm3 = async ({ selectedOptions }) => {
  if (status.value === 0) {
    option3.value = selectedOptions[0]?.text;
    show_option3.value = false;
    //重置
    option4.value = "";
    option4_list.value = [];

    let params = {
      school: option2.value,
      subject: option3.value,
    };
    const res = await api.getMajor(params);
    option4_list.value = [
      ...res.map((item, index) => ({
        text: item,
        value: index + 1,
      })),
    ];
  }
};

//选项4
const option4 = ref("");
const show_option4 = ref(false);
const option4_list = ref([]);
//同理，渲染选项4_list
const onOptionConfirm4 = async ({ selectedOptions }) => {
  if (status.value === 0) {
    option4.value = selectedOptions[0]?.text;
    show_option4.value = false;
  }
};

const onSubmit = async (values) => {
  if (status.value === 0) {
    let enrollForm = values;
    enrollForm = {
      ...enrollForm,
      id: enrollId.value,
      sex: sex.value,
      option1: option1.value,
      option2: option2.value,
      option3: option3.value,
      option4: option4.value,
    };

    let res = await api.postEnrollInfo(enrollForm);
    if (res === "报名信息提交成功") dialog_show.value = true;
  }
};

//弹窗
const dialog_show = ref(false);
const toPay = async () => {
  let params = {
    id: enrollId.value,
    redirectUrl: "",
    backUrl: "",
  };
  const res = await api.postPay(params);
  window.location.href = res.url;

  dialog_show.value = false;
};

onMounted(async () => {
  if (userData.value) {
    name.value = userData.value.name;
    phone.value = userData.value.phone;
    cardno.value = userData.value.cardno;
    await get_EnrollInfo();
  }
  //缴费后进入页面跳出弹窗
  if (payStatus.value === 1) {
    showDialog({
      title: "您已缴费成功！",
      message: "请保持电话畅通，耐心等待工作人员联系。",
    }).then(() => { });
  }

  //完成报名
  if (stepActive.value === 4) {
    showDialog({
      title: "您已报名成功！",
      message: "请保持电话畅通，耐心等待工作人员联系。",
    }).then(() => { });
  }
});
</script>

<template>
  <div class="enroll-container">
    <van-nav-bar title="填写报名信息" style="margin: 20px 0" />
    <header>
      <Steps :stepActive="stepActive" />
    </header>
    <main>
      <van-form class="form" @submit="onSubmit">
        <!--        姓名-->
        <van-field class="field-box" v-model="name" name="name" input-align="center" :readonly="status === 1"
          placeholder="请填写您的真实姓名" />
        <!--性别-->
        <div class="sex-container">
          <div :class="['sex-box', sex === '男生' ? 'sex-active' : '']" @click="status === 0 && setSex('男生')"
            :style="{ cursor: status === 0 ? 'pointer' : 'not-allowed' }">
            男生
          </div>
          <div :class="['sex-box', sex === '女生' ? 'sex-active' : '']" @click="status === 0 && setSex('女生')"
            :style="{ cursor: status === 0 ? 'pointer' : 'not-allowed' }">
            女生
          </div>
        </div>
        <!--手机号-->
        <van-field class="field-box" v-model="phone" name="phone" input-align="center" placeholder="请填写本人的手机号"
          :style="{ color: status === 1 ? '#c8c9d6' : 'black' }" :readonly="status === 1"/>
        <!--        民族+籍贯-->
        <div class="info-container">
          <van-field is-link class="info-box" v-model="nation" arrow-direction="down" name="nation" input-align="center"
            readonly :disabled="status === 1" placeholder="民族" @click="status === 0 && (showNation = true)" />
          <van-popup v-model:show="showNation" position="bottom">
            <van-picker :columns="nationList" @confirm="onNationConfirm" @cancel="showNation = false" />
          </van-popup>
          <van-field is-link class="info-box" v-model="place" readonly arrow-direction="down" name="place"
            input-align="center" placeholder="籍贯（省/市）" @click="status === 0 && (showArea = true)" />
          <van-popup v-model:show="showArea" position="bottom">
            <van-area :area-list="areaList" @confirm="onPlaceConfirm" @cancel="showArea = false" />
          </van-popup>
        </div>
        <!--身份证-->
        <van-field class="field-box" v-model="cardno" name="cardno" input-align="center" :readonly="status === 1"
          :style="{ color: status === 1 ? '#c8c9d6' : 'black' }" placeholder="请填写本人的身份证号" />

        <!--        专升本-->
        <div class="sex-container">
          <div :class="['sex-box', option1 === '专升本' ? 'sex-active' : '']" @click="status === 0 && setOption1('专升本')"
            :style="{ cursor: status === 0 ? 'pointer' : 'not-allowed' }">
            专升本
          </div>
          <div :class="['sex-box', option1 === '高起专' ? 'sex-active' : '']" @click="status === 0 && setOption1('高起专')"
            :style="{ cursor: status === 0 ? 'pointer' : 'not-allowed' }">
            高起专
          </div>
        </div>

        <!--        院校-->
        <van-field is-link class="field-box" v-model="option2" arrow-direction="down" name="option2" readonly
          :disabled="status === 1" placeholder="请选择报名院校" @click="status === 0 && (show_option2 = true)" />
        <van-popup v-model:show="show_option2" position="bottom">
          <van-picker :columns="option2_list" @confirm="onOptionConfirm2" @cancel="show_option2 = false" />
        </van-popup>

        <!--        科类-->
        <van-field is-link class="field-box" v-model="option3" arrow-direction="down" name="option3" readonly
          :disabled="status === 1" placeholder="请选择报名科类" @click="status === 0 && (show_option3 = true)" />
        <van-popup v-model:show="show_option3" position="bottom">
          <van-picker :columns="option3_list" @confirm="onOptionConfirm3" @cancel="show_option3 = false" />
        </van-popup>

        <!--        专业-->
        <van-field is-link class="field-box" v-model="option4" arrow-direction="down" name="option4" readonly
          :disabled="status === 1" placeholder="请选择报名科类" @click="status === 0 && (show_option4 = true)" />
        <van-popup v-model:show="show_option4" position="bottom">
          <van-picker :columns="option4_list" @confirm="onOptionConfirm4" @cancel="show_option4 = false" />
        </van-popup>

        <div style="margin: 16px">
          <van-button round block type="primary" native-type="submit" :disabled="status === 1"
            style="background-color: #4b79e3">
            确认提交（￥{{ enrollPrice }}）
          </van-button>
        </div>
      </van-form>
    </main>

    <van-dialog v-model:show="dialog_show" title="填写报名信息成功" confirmButtonText="前往缴付" @confirm="toPay">
      <van-icon class="icon" name="success" color="#3b8af8" size="30" />
    </van-dialog>
  </div>
</template>

<style scoped lang="less">
@import url("@/styles/enroll/enroll");
</style>